package com.wedimob.slideshare.task.cpu;

import org.jsoup.nodes.Document;

import com.wedimob.slideshare.Factory;
import com.wedimob.slideshare.WriteType;
import com.wedimob.slideshare.bo.Summaries;
import com.wedimob.slideshare.bo.Summary;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.Task;
import com.wedimob.slideshare.task.io.network.TaskHtmlDownloader;

public class TaskSummariesExtractor extends
        Task<Document, Summaries> {

    private WriteType write;
    private boolean recursiveMode;

    public TaskSummariesExtractor(PoolExecutor pool,
            Document input, boolean recursiveMode, WriteType write, int limit, int timeout) {
        super(pool, input, limit, timeout);
        this.recursiveMode = recursiveMode;
        this.write = write;
    }

    @Override
    public void run() {
        try {
            output = Factory.fromDocument(input, Summaries.class, null);

            for (Summary summary : output) {
                pool.getResults().putResult(summary);

                if (recursiveMode) {
                    pool.execAsync(new TaskHtmlDownloader(pool, summary, write, timeout));
                }

                if (limit > 0 && pool.getResults().getNbResultType(Summary.class) >= limit) {
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }

}
